package com.task.controller.executor.impl;

import com.task.controller.entity.Mission;
import com.task.controller.executor.Executor;
import com.task.controller.manager.impl.CurrentMethodManager;
import com.task.controller.param.ParamParser;
import ohos.app.Context;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.NoSuchElementException;

public class CurrentExecutor implements Executor {

    private static CurrentExecutor currentExecutor = new CurrentExecutor();

    private CurrentExecutor() {
        super();
    }

    public static CurrentExecutor getInstance() {
        if (currentExecutor == null) {
            currentExecutor = new CurrentExecutor();
        }
        return currentExecutor;
    }

    @Override
    public void execute(Context context, String resource, Object o, ExecuteEvent executeEvent) {
        Mission mission = CurrentMethodManager.getInstance().lookup(resource);
        if (mission == null) {
            throw new NoSuchElementException("没有对应的资源");
        }
        Method method = mission.getMethod();
        ParamParser parse = mission.getParse();
        Object instance = mission.getObject();
        Object obj = parse.parse(context, o, method);
        method.setAccessible(true);
        Object result = null;
        try {
            if (obj == null) {
                result = method.invoke(instance);
            } else if (obj instanceof List) {
                result = method.invoke(instance, ((List<?>) obj).toArray());
            } else if (obj instanceof Object[]) {
                result = method.invoke(instance, (Object[]) obj);
            } else {
                result = method.invoke(instance, obj);
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        if (executeEvent != null) {
            executeEvent.executeListener(result);
        }
    }
}
